package com.aiyige.page.pay.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;

import com.aiyige.BuildConfig;
import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiUrls;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.User;
import com.aiyige.model.eshop.CodeMsg;
import com.aiyige.model.eshop.Order;
import com.aiyige.model.eshop.OrderCreateModel;
import com.aiyige.model.eshop.ProductsBackup;
import com.aiyige.model.request.CreateOrderRequest;
import com.aiyige.model.request.GetOrderDetailByMomentidRequest;
import com.aiyige.model.request.GetUnpaidRequest;
import com.aiyige.model.request.OrderChangeQuantityRequest;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.model.response.OrderCreateResponse;
import com.aiyige.page.login.LoginPage;
import com.aiyige.page.login.callbacks.ILoginCallBack;
import com.aiyige.page.login.model.impl.LoginManager;
import com.aiyige.page.pay.model.OrderModel;
import com.aiyige.page.pay.model.PayResult;
import com.aiyige.page.pay.model.UnpayModel;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.CommonTitleDetailDialog;
import com.alibaba.android.arouter.launcher.ARouter;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

import static com.aiyige.page.pay.ConfirmOrderPage.REQUEST_CODE_CONFIRM_PAY;

/**
 * Created by zhuyakun on 2018/1/29.
 */

public class PayUtil {
    public static final String ACTION_WECHAT_PAY_RESULT = "com.aiyige.action.pay.ACTION_WECHAT_PAY_RESULT";
    public static final String EXTRA_KEY_WECHAT_PAY_RESULT_CODE = "com.aiyige.extra.pay.EXTRA_KEY_WECHAT_PAY_RESULT_CODE";
    public static final String EXTRA_KEY_WECHAT_PAY_RESULT_MSG = "com.aiyige.extra.pay.EXTRA_KEY_WECHAT_PAY_RESULT_MSG";
    public static final String ACTION_ALIPAY_RESULT = "com.aiyige.action.pay.ACTION_ALIPAY_RESULT";
    public static final String EXTRA_KEY_ALIPAY_RESULT = "com.aiyige.extra.pay.EXTRA_KEY_ALIPAY_RESULT";
    public static final int PAY_RESULT_SUCCEED = 1;
    public static final int PAY_RESULT_FAILED = 2;
    public static final String CONFIRM_PAY_ACTION_TYPE_NEW_ORDER = "CONFIRM_PAY_ACTION_TYPE_NEW_ORDER";
    public static final String CONFIRM_PAY_ACTION_TYPE_CONTINUE_PAY = "CONFIRM_PAY_ACTION_TYPE_CONTINUE_PAY";

    public static final String ACTION_PAY_RESULT = "com.aiyige.action.ACTION_PAY_RESULT";
    public static final String EXTRA_KEY_PAY_RESULT_DATA = "com.aiyige.extra.EXTRA_KEY_PAY_RESULT_DATA";


    /**
     * 教学视频类型的支付
     */
    public static final int TYPE_LEARN_VIDEO = 1;
    /**
     * 课程类型的支付
     */
    public static final int TYPE_COURSE = 2;


    private static List<UnpayModel> unpayModelList;

    public static void payWithWX(String appId, String partnedId, String prepayId, String packageValue, String nonceStr, String timeStamp, String sign) {
        IWXAPI api = WXAPIFactory.createWXAPI(MyApp.getAppContext(), null);
        PayReq request = new PayReq();
        request.appId = appId;
        request.partnerId = partnedId;
        request.prepayId = prepayId;
        request.packageValue = packageValue;
        request.nonceStr = nonceStr;
        request.timeStamp = timeStamp;
        request.sign = sign;
        api.sendReq(request);
    }

    public static PayResult obtainPayResult(Intent data) {
        return data.getParcelableExtra(EXTRA_KEY_PAY_RESULT_DATA);
    }

    public static AlertDialog.Builder cancelOrderDialog(Context context) {
        return new AlertDialog.Builder(context)
                .setTitle(R.string.remind)
                .setMessage(R.string.confirm_cancel_order)
                .setCancelable(true);
    }

    public static AlertDialog.Builder cancelPayDialog(Context context) {
        return new AlertDialog.Builder(context)
                .setTitle(R.string.remind)
                .setMessage(R.string.confirm_cancel_pay)
                .setCancelable(true);
    }

    public static AlertDialog.Builder repeatPayAlertDialog(Context context) {
        return new AlertDialog.Builder(context)
                .setTitle(R.string.remind)
                .setMessage(R.string.you_have_bought_this_goods_can_not_repeat_buy)
                .setCancelable(false);
    }

    public static boolean checkWeChatPaySupport() {
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(MyApp.getAppContext(), null);
        return iwxapi.isWXAppInstalled() && iwxapi.isWXAppSupportAPI();
    }


    /**
     * 支付接口
     *
     * @param type
     */
    public static void pay(final int type, final String momentId, final int version, final PayCallback payCallback) {
        if (!LoginManager.isLogin()) {
            LoginPage.start();
            LoginManager.getInstance().addLoginCallBack(new ILoginCallBack() {
                @Override
                public void success(User userInfo) {
                    pay(type, momentId, version, payCallback);
                }

                @Override
                public void error(String errorCode) {

                }
            });
            return;
        }
        User user = AccountUtil.getCurrentUser();
        if (user != null && TextUtils.isEmpty(user.getMobile())) {
            ARouter.getInstance().build(ARouterConfig.BindingPhonePage).navigation();
            return;
        }
        if (TextUtils.isEmpty(momentId)) {
            return;
        }
        if (type == TYPE_LEARN_VIDEO || type == TYPE_COURSE) {
            GetOrderDetailByMomentidRequest.newBuilder().momentId(momentId).version(version).build().enqueue(new retrofit2.Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.isSuccessful()) {
                        try {
                            String json = response.body().string();
                            Log.v("", json);
                            CodeMsg codeMsg = JsonUtil.toObject(json, CodeMsg.class);

                            if (codeMsg != null) {
                                switch (codeMsg.code) {
                                    // 正常 没有购买过
                                    case OrderVerifyStatus.NORMAL_0:
                                        ARouter.getInstance()
                                                .build(ARouterConfig.ConfirmOrderPage)
                                                .withString("goodsId", momentId)
                                                .withString("source", "app")
                                                .withString("sourceUrl", ApiUrls.BaseUrl)
                                                .navigation();
                                        break;
                                    // 已经购买了（比如再次之前的时间里发生了购买）
                                    case OrderVerifyStatus.BUYED_1:
                                        ToastX.show(codeMsg.msg);
                                        if (payCallback != null) {
                                            payCallback.payed();
                                        }
                                        break;
                                    // 由于卖家等情况，订单商品发生了变化，比如价格变化，需要重新刷新并让用户点击购买
                                    case OrderVerifyStatus.CHANGED_2:
                                        ToastX.show(codeMsg.msg);
                                        if (payCallback != null) {
                                            payCallback.momentChanged();
                                        }
                                        break;
                                }

                            }


//
                        } catch (IOException e) {

                        }
                    } else {
                        if (response != null) {
                            ErrorResponse errorResponse = ErrorUtil.handleErrorResponse(response);
                            if (errorResponse != null && !TextUtils.isEmpty(errorResponse.getCode())) {
                                switch (errorResponse.getCode()) {
                                    case ResponseCode.DO_NOT_REPEAT_PAY://重复支付
                                        if (payCallback != null) {
                                            payCallback.payed();
                                        }
                                        break;
                                    case ResponseCode.DO_NOT_BUY_SELF_GOODS://订单验证失败，卖家不用购买自己的商品{0}！
                                        break;
                                    case ResponseCode.ORDER_GOODS_IS_EMPTY:
                                        break;
                                    case ResponseCode.UNDERSTOCK:
                                        if (payCallback != null) {
                                            payCallback.momentChanged();// 订单确认页会刷新
                                        }
                                        break;
                                    case ResponseCode.CLASS_IS_STARTED://#您购买的课程已经开课，已无法购买！
                                        break;
                                    case ResponseCode.MOMENT_HAS_CHANGED_PLEASE_CREATE_NEW_ORDER://#该商品信息发生变更，请重新下单！
                                        if (payCallback != null) {
                                            payCallback.momentChanged();// 订单确认页会刷新
                                        }
                                        break;
                                    case ResponseCode.SELL_OUT://#该商品已经售罄！
                                        if (payCallback != null) {
                                            payCallback.momentChanged();// 订单确认页会刷新
                                        }
                                        break;
                                }
                                ToastX.show(errorResponse.getMessage());
                            }
                        }
                    }

                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });


        }

    }

    /**
     * @param orderModel
     * @param count
     * @param tid         推广id
     * @param code        推广跳转次数，从0开始计数
     * @param payCallback
     * @param activity
     */
    public static void createOrder(final OrderModel orderModel, int count, String couponId, String tid, int code, final PayCallback payCallback, final BaseActivity activity) {
        if (orderModel == null) {
            return;
        }
        List<ProductsBackup> productsBackupList = new LinkedList<>();
        ProductsBackup productsBackup = new ProductsBackup();
        productsBackup.setMomentId(orderModel.getGoodsId());
        productsBackup.setCount(count);
        productsBackup.setVersion(orderModel.getVersion());
        productsBackupList.add(productsBackup);
        // 创建者信息
        String sellerId;
        sellerId = orderModel.getSellerId();
        OrderCreateModel model = OrderCreateModel.newBuilder()
                .sellerId(sellerId)
                .sourceUrl(ApiUrls.BaseUrl)
                .subject(orderModel.getSubject())
                .version(orderModel.getVersion())
                .userCouponIds(TextUtils.isEmpty(couponId)?null:Arrays.asList(couponId))
                .productsBackup(productsBackupList).build();
        if (activity != null) {
            activity.showLoading();
        }
        CreateOrderRequest.newBuilder()
                .orderCreateModel(model)
                .tid(tid)
                .code(code)
                .build()
                .enqueue(new retrofit2.Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (activity != null) {
                            activity.hideLoading();
                        }
                        if (response.isSuccessful()) {
                            try {
                                String json = response.body().string();
                                Log.v("", json);
                                OrderCreateResponse orderResponse = JsonUtil.toObject(json, OrderCreateResponse.class);
                                if (orderResponse != null && orderResponse.getOrder() != null) {

                                    Order order = orderResponse.getOrder();
                                    orderModel.setOrderId(order.getId());
                                    ARouter.getInstance()
                                            .build(ARouterConfig.ConfirmPayPage)
                                            .withParcelable("orderModel", orderModel)
                                            .navigation(activity, REQUEST_CODE_CONFIRM_PAY);
                                }
                            } catch (IOException e) {

                            }
                        } else {
                            if (response != null) {
                                ErrorResponse errorResponse = ErrorUtil.handleErrorResponse(response);
                                if (errorResponse != null && !TextUtils.isEmpty(errorResponse.getCode())) {
                                    ToastX.show(errorResponse.getMessage());
                                    switch (errorResponse.getCode()) {
                                        case ResponseCode.DO_NOT_REPEAT_PAY://重复支付
                                            if (payCallback != null) {
                                                payCallback.payed();
                                            }
                                            break;
                                        case ResponseCode.DO_NOT_BUY_SELF_GOODS://订单验证失败，卖家不用购买自己的商品{0}！
                                        case ResponseCode.ORDER_GOODS_IS_EMPTY:///#订单中的商品不能为空！
                                        case ResponseCode.UNDERSTOCK:// 订单确认页会刷新
                                        case ResponseCode.CLASS_IS_STARTED://#您购买的课程已经开课，已无法购买！
                                        case ResponseCode.MOMENT_HAS_CHANGED_PLEASE_CREATE_NEW_ORDER://#该商品信息发生变更，请重新下单！
                                        case ResponseCode.SELL_OUT://#该商品已经售罄！
                                            if (payCallback != null) {
                                                payCallback.momentChanged();// 订单确认页会刷新
                                            }
                                            break;
                                    }

                                }
                            }
                        }

                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });

    }

    public static void changeQuantity(final OrderModel orderModel, int count, final PayCallback payCallback, final Activity activity) {
        if (orderModel == null) {
            return;
        }
        List<ProductsBackup> productsBackupList = new LinkedList<>();
        ProductsBackup productsBackup = new ProductsBackup();
        productsBackup.setMomentId(orderModel.getGoodsId());
        productsBackup.setCount(count);
        productsBackup.setVersion(orderModel.getVersion());
        productsBackupList.add(productsBackup);
        Order order = new Order();
        order.setProductsBackup(productsBackupList);
        order.setCount(count);
        order.setMomentId(orderModel.getGoodsId());
        OrderChangeQuantityRequest.newBuilder().order(order).build().enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        String json = response.body().string();
                        Log.v("", json);
                        OrderCreateResponse orderResponse = JsonUtil.toObject(json, OrderCreateResponse.class);
                        if (orderResponse != null && orderResponse.getOrder() != null) {

                            Order order = orderResponse.getOrder();
                            orderModel.setOrderId(order.getId());
                            ARouter.getInstance()
                                    .build(ARouterConfig.ConfirmPayPage)
                                    .withParcelable("orderModel", orderModel)
                                    .navigation(activity, REQUEST_CODE_CONFIRM_PAY);
                        }
                    } catch (IOException e) {

                    }
                } else {
                    if (response != null) {
                        ErrorResponse errorResponse = ErrorUtil.handleErrorResponse(response);
                        if (errorResponse != null && !TextUtils.isEmpty(errorResponse.getCode())) {
                            switch (errorResponse.getCode()) {
                                case ResponseCode.DO_NOT_REPEAT_PAY://重复支付
                                    if (payCallback != null) {
                                        payCallback.payed();
                                    }
                                    break;
                                case ResponseCode.DO_NOT_BUY_SELF_GOODS://订单验证失败，卖家不用购买自己的商品{0}！
                                    break;
                                case ResponseCode.ORDER_GOODS_IS_EMPTY:
                                    break;
                                case ResponseCode.UNDERSTOCK:
                                    if (payCallback != null) {
                                        payCallback.momentChanged();// 订单确认页会刷新
                                    }
                                    break;
                                case ResponseCode.CLASS_IS_STARTED://#您购买的课程已经开课，已无法购买！
                                    break;
                                case ResponseCode.MOMENT_HAS_CHANGED_PLEASE_CREATE_NEW_ORDER://#该商品信息发生变更，请重新下单！
                                    if (payCallback != null) {
                                        payCallback.momentChanged();// 订单确认页会刷新
                                    }
                                    break;
                                case ResponseCode.SELL_OUT://#该商品已经售罄！
                                    if (payCallback != null) {
                                        payCallback.momentChanged();// 订单确认页会刷新
                                    }
                                    break;
                            }
                            ToastX.show(response.message());
                        }
                    }
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

    }


    // 验证结果状态：
    // 验证结果 0-正常 1-已经购买 2-商品有变更
    private class OrderVerifyStatus {
        public static final int NORMAL_0 = 0;
        public static final int BUYED_1 = 1;
        public static final int CHANGED_2 = 2;
    }

    public interface PayCallback {
        void payed();

        void momentChanged();
    }


    /**
     * App启动检查是否有未支付的费用（补交手续费）
     *
     */
    public static void checkUnpaid(final FragmentActivity activity) {
        User user = AccountUtil.getCurrentUser();
        GetUnpaidRequest.newBuilder().build().enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response != null && response.isSuccessful()) {
                    try {
                        String json = response.body().string();
                        Log.v("", json);
                        List<UnpayModel> unpayModelList = JsonUtil.toObjectList(json, UnpayModel.class);
                        PayUtil.unpayModelList = unpayModelList;
                        if (hasUnpay()) {
                            final UnpayModel unpayModel = getUnpayModel();
                            CommonTitleDetailDialog.newInstance(getString(R.string.pay_service_charge),unpayModel.getUserFeeDescription(),null,getString(R.string.to_pay))
                                    .setBackPressEnable(BuildConfig.DEBUG?true:false).setListener(new CommonTitleDetailDialog.Listener() {
                                @Override
                                public void onConfirmClassed() {
                                    ARouter.getInstance().build(ARouterConfig.ConfirmPayPage).withParcelable("unpayModel",unpayModel).withBoolean("isServiceChargePay", true).navigation();
                                }
                            }).show(activity.getSupportFragmentManager(),"");
                        }


                    } catch (Exception e) {
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

//    private OrderModel getOrderModel(UnpayModel unpayModel) {
//        if (unpayModel == null) {
//            return null;
//        }
//        User user = AccountUtil.getCurrentUser();
//        OrderModel orderModel = OrderModel.newBuilder()
////                .contentCountString("1")
////                .version()
//                .buyNum(1)
//                .coverUrl(ListUtil.isEmpty(unpayModel.getCover())?null:unpayModel.getCover().get(0))
//                .goodsId(unpayModel.getId())
////                .guaranteeItemList()
//                .orderId(unpayModel.getOrderId())
//                .sellerAvatar(user.getAvatar())
//                .sellerId(user.getId())
//                .sellerName(user.getAccount())
//                .singlePrice(unpayModel.get)
//                .source()
//                .sourceUrl()
//                .subject()
//                .subjectIndex()
//                .title()
//                .totalPayPrice()
//                .totalPrice()
//                .build();
//        return orderModel;
//    }

    private static String getString(int strId) {
        return MyApp.getAppContext().getString(strId);
    }

    /**
     * 是否有未支付的手续费
     * @return
     */
    public static boolean hasUnpay() {
        return !ListUtil.isEmpty(unpayModelList);
    }


    /**
     * 把支付成功的记录删掉
     * @return
     */
    public static void removePaidOrder(String orderId) {
        if (TextUtils.isEmpty(orderId)) {
            return;
        }
        if (!ListUtil.isEmpty(unpayModelList)) {
            for (int i=0;i<unpayModelList.size();i++) {
                if (orderId.equals(unpayModelList.get(i).getId())) {
                    unpayModelList.remove(i);
                    break;
                }
            }
        }
    }

    public static UnpayModel getUnpayModel() {
        return hasUnpay()?unpayModelList.get(0):null;
    }



}
